package com.zhengwl.study.aop;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.Translator;

public class MyTranslator implements Translator {

	@Override
	public void onLoad(ClassPool pool, String classname) throws NotFoundException, CannotCompileException {
		if (!"model$Worker".equals(classname)) {
			return;
		}
		// 通过获取类文件
		try {
			CtClass cc = pool.get(classname);
			// 获得指定方法名的方法
			CtMethod m = cc.getDeclaredMethod("doSomeThing");
			// 在方法执行前插入代码
			m.insertBefore("{ System.out.println(\"记录日志\"); }");
		} catch (NotFoundException | CannotCompileException e) {
		}
	}

	@Override
	public void start(ClassPool pool) throws NotFoundException, CannotCompileException {

	}

	public static void main(String[] args) {
		Worker b = new Worker();
		b.doWork();
		b.doSleep();
	}

}
